package com.miku.ai.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.miku.ai.common.ErrorCode;
import com.miku.ai.exception.ThrowUtils;
import com.miku.ai.model.dto.question.QuestionContentDTO;
import com.miku.ai.model.entity.App;
import com.miku.ai.model.entity.Question;
import com.miku.ai.model.entity.ScoringResult;
import com.miku.ai.model.entity.UserAnswer;
import com.miku.ai.model.enums.AppTypeEnum;
import com.miku.ai.model.vo.QuestionVO;
import com.miku.ai.service.AppService;
import com.miku.ai.service.QuestionService;
import com.miku.ai.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * 打分类应用
 */
@ScoringSrategyConfig(appType = 0,scoringStrategy = 0)
public class CustomScoreScoringStrategy implements ScoringStrategy {

    @Resource
    private QuestionService questionService;

    @Resource
    private AppService appService;

    @Resource
    private ScoringResultService scoringResultService;
    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        //1.根据id 查询到题目和题目结果信息（按照分数降序排序）
        Long appId = app.getId();
        ThrowUtils.throwIf(appId == null, ErrorCode.PARAMS_ERROR);
        Question question = questionService.getOne(Wrappers.<Question>lambdaQuery().eq(Question::getAppId, appId));
        List<ScoringResult> scoringResults = scoringResultService.list(Wrappers.<ScoringResult>lambdaQuery()
                .eq(ScoringResult::getAppId, appId)
                .orderByDesc(ScoringResult::getResultScoreRange)
        );
        //2.统计用户总得分
        //初始化HashMap，用于存储每个选项的个数
        int totalScore = 0;
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();
        //遍历题目列表
        for (QuestionContentDTO questionContentDTO : questionContent) {
            //遍历答案列表
            for (String answer : choices) {
                for (QuestionContentDTO.Option option : questionContentDTO.getOptions()) {
                    //如果答案和选型key相匹配
                    if (answer.equals(option.getKey())) {
                        int score = Optional.of(option.getScore()).orElse(0);
                        //将选型result的值累加到总得分
                        totalScore += score;
                    }
                }
            }
        }
        //3.遍历得分结果,找到第一个用户分数大于得分范围的结果，作为最终结果
        ScoringResult maxScoreResult = scoringResults.get(0);
        for (ScoringResult scoringResult : scoringResults) {
            if (totalScore>=scoringResult.getResultScoreRange()){
                maxScoreResult = scoringResult;
                break;
            }
        }
        //4.构造返回结果，填充答案对象属性

        UserAnswer userAnswer=new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoreResult.getId());
        userAnswer.setResultName(maxScoreResult.getResultName());
        userAnswer.setResultDesc(maxScoreResult.getResultDesc());
        userAnswer.setResultPicture(maxScoreResult.getResultPicture());
        userAnswer.setResultScore(totalScore);
        return userAnswer;
    }
}
